#include <signal.h>
#include "udp_server.hpp"
using func_t = function<void(const string&name)>;
sockaddr_in server;
socklen_t len = sizeof(server);
int fd = -1;

void Handler(int signo){
    if (signo != 2) return;
    string messages = "我走了你们聊";
    sendto(fd,messages.c_str(),messages.size(),0,CONV(&server),len);    
    messages = "QUIT";
    sendto(fd,messages.c_str(),messages.size(),0,CONV(&server),len);
    exit(0);
}

int main(int argc,char* argv[]){
    signal(2,Handler);
    // if (argc != 3){
    //     Useage("Please use: ./clietn + server_ip + server_port");
    //     exit(1);
    // }
    fd = ::socket(AF_INET,SOCK_DGRAM,0);
    if (fd < 0){
        LOG(ERROR) << "socket create error";
        exit(fd);
    }
    //初始化服务端信息, 注意这里不是用来bind的, 而是直接用来发送的
    
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);  
    server.sin_family = AF_INET;
    server.sin_port = ::htons(port);
    server.sin_addr.s_addr = ::inet_addr(ip.c_str());
    
    Thread t([&](const string& name){
        while(1){
            sockaddr_in peer;
            memset(&peer,0,sizeof(peer));
            socklen_t Len = sizeof(peer);
            char inbuffer[1024];
            ssize_t n  =  recvfrom(fd,inbuffer,1024,0,CONV(&peer),&Len);
            //ber??? 你是傻逼吗? 对方是谁啊?? 不就是我们那个机器的服务端吗? 所以为什么你两台机器收到的信息都是
            //不重复的?? 不同是在哪啊?? 在我们发送端啊, 傻逼!!! 
            InetAddr client(peer);
            if (n > 0){
                inbuffer[n] = 0;
                cerr << inbuffer << endl;
            }
        }
    });
    //ber是, 你要启动自己的线程啊??
    t.Start();
    //直接与主线程分离
    t.Detach();
    string messgae;
    while(1){
        LOG(INFO) << "Please enter";
        getline(cin,messgae);
        if (messgae.size() == 0) messgae += '\n';
        sendto(fd,messgae.c_str(),messgae.size(),0,CONV(&server),len);
    }
    return 0;
}